package com.nexmo.hangman.service.impl;

import com.nexmo.hangman.dao.UserDao;
import com.nexmo.hangman.domain.User;
import com.nexmo.hangman.domain.dto.UserDto;
import com.nexmo.hangman.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service()
public class UserServiceImpl implements UserService {

    private final UserDao userDao;

    @Autowired
    public UserServiceImpl(UserDao userDao) {
        this.userDao = userDao;
    }


    @Override
    @Transactional
    public UserDto findByName(String userName) {
        User user = userDao.findByName(userName);
        return user == null ? null : buildUserDto(user);
    }

    @Override
    @Transactional
    public UserDto create(String userName) {
        User newUser = new User();
        newUser.setName(userName);
        userDao.save(newUser);
        return buildUserDto(newUser);
    }

    private UserDto buildUserDto(User user) {
        return UserDto.fromUser(user);
    }
}
